import tkinter as tk
from tkinter import messagebox
from db import db
from MainPage import MainPage




class LoginPage:
        def __init__(self,master):
            self.root = master
            self.root.geometry("500x320")
            self.root.title('管理员登录')

            self.LoginPage = tk.Frame(root)
            self.LoginPage.pack()
            self.root.resizable(0, 0)

            self.username = tk.StringVar()
            self.password = tk.StringVar()

            tk.Label(self.LoginPage,text="管理员登陆",font=("黑体",18)).grid(row=0,column=2,padx=60)
            tk.Label(self.LoginPage,text="账号：",font=("黑体",12)).grid(row=1,column=1,pady=20)
            tk.Entry(self.LoginPage,width=35,font=("黑体",10),textvariable=self.username).grid(row=1,column=2,ipady=10)
            tk.Label(self.LoginPage,text="密码：",font=("黑体",12)).grid(row=2,column=1,pady=20)
            tk.Entry(self.LoginPage,width=35,font=("黑体",10),textvariable=self.password).grid(row=2,column=2,ipady=10)
            tk.Button(self.LoginPage, text="登陆",font=("黑体",14),width=20,command=self.login).grid(row=4,column=2,pady=30)
            tk.Button(self.LoginPage, text="退出",font=("黑体",14,),command=self.close).grid(row=6,column=3)
            tk.Button(self.LoginPage,text="还没有管理员账户？点击注册！",font=("黑体",10,'underline'),bd=0,activeforeground='blue',command=self.Register).grid(row=5,column=2)


        def login(self):
            
        
            name =self.username.get()
            pwd =self.password.get()
            flag, message= db.check_login(name,pwd)
            if not all([name,pwd]):
                miss = [field for field,value in zip(['姓名', '密码'], 
                                                       [name, pwd]) if not value]
                messagebox.showerror("错误", f"请填写以下字段: {', '.join(miss)}")
                return
            if flag:
                self.LoginPage.destroy()
                MainPage(self.root)
                messagebox.showinfo(title='成功',message=message)
            else:
                messagebox.showwarning(title='警告',message=message)
        

        def Register(self):
             messagebox.showinfo(title='注册',message='请联系管理员进行注册')
        def close(self):
            if tk.messagebox.askokcancel("退出", "你确定要退出吗?"):
                root.destroy()
              








if __name__ == '__main__':
      root = tk.Tk()
      LoginPage(master=root)
      root.mainloop()   